package sbt.wikipedia;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.swing.*;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.annotations.SerializedName;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import javax.xml.bind.DatatypeConverter;

/**
 * This is a starting point for querying the wikipedia API.
 * <p>
 * Feel free to augment/improve this class to fit your needs.
 * 
 * @author pa
 *
 */
public class WikipediaCollector {
	static private Gson gson = new Gson();
	static private JsonParser parser = new JsonParser();
	static public String WP_API = "http://en.wikipedia.org/w/api.php"; 

	/**
	 * Load a JsonObject from the given URL.
	 * @param url  the URL
	 * @return  the JSON object parsed from the URL
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	static public JsonObject loadJson(String url)
			throws MalformedURLException, IOException {
		URLConnection connection = new URL(url).openConnection();
		connection.setRequestProperty("Accept-Charset", "utf-8");
		Reader reader = new InputStreamReader(connection.getInputStream());
		return parser.parse(reader).getAsJsonObject();
	}
	
        static  String buildURLRev(String topic, String limit,String property) throws UnsupportedEncodingException{
                String format = URLEncoder.encode("json", "UTF-8");
		String action = URLEncoder.encode("query", "UTF-8");
		String titles = URLEncoder.encode(topic, "UTF-8");
		String prop = URLEncoder.encode("revisions", "UTF-8");
		String rvlimit = URLEncoder.encode(limit, "UTF-8");
		String url = String.format(
				"%s?format=%s&action=%s&titles=%s&prop=%s&rvlimit=%s",
				WP_API, format, action, titles, prop, rvlimit);
		System.err.println(url);
				
		return url;
        }
        
        static  String buildURL(String topic,String property, String subProps) throws UnsupportedEncodingException{
                String format = URLEncoder.encode("json", "UTF-8");
		String action = URLEncoder.encode("query", "UTF-8");
		String titles = URLEncoder.encode(topic, "UTF-8");
		String prop = URLEncoder.encode(property, "UTF-8");
		String url = String.format(
				"%s?format=%s&action=%s&titles=%s&prop=%s%s",
				WP_API, format, action, titles, prop, subProps);
		System.err.println(url);
				
		return url;
        }
        
	

        
        public static String getPageBasedOn(String pageName) throws Throwable{
            String url=buildURL(pageName,"revisions","&rvprop=content&rvsection=0");
            
            int indexInContent, indexTemplateEnd;
            
            JsonObject response = loadJson(url);
            WpQuery query = gson.fromJson(
                            response.getAsJsonObject("query"), WpQuery.class);
            WpPage page = (WpPage)(query.pages.values().toArray()[0]);
            
            String content = page.revisions.get(0).content;
            String templateBasedOn = "{{based on|\'\'[[";
          
            System.out.println(content);
            
            indexInContent = content.indexOf(templateBasedOn);
            if(indexInContent == -1){
                templateBasedOn = "{{Based on|\'\'[[";
                indexInContent = content.indexOf(templateBasedOn);
            }
            
            if(indexInContent == -1){
                templateBasedOn = "{{basedon|\'\'[[";
                indexInContent = content.indexOf(templateBasedOn);
            }
            
            if(indexInContent == -1){
                return "";
            }
            
            indexTemplateEnd = content.indexOf(templateBasedOn)+templateBasedOn.length();

            String result = content.substring(indexTemplateEnd,content.indexOf(']', indexTemplateEnd));

            String[] listResults = result.split("\\|");
            
            
            
            
            return listResults[0];
        }
        
        public static Date getPageCreationTimeStamp(String pageName) throws Throwable{
            String url=buildURL(pageName,"revisions","&rvprop=timestamp&rvdir=newer&rvlimit=1");
            JsonObject response = loadJson(url);
            WpQuery query = gson.fromJson(
                            response.getAsJsonObject("query"), WpQuery.class);
            WpPage page = (WpPage)(query.pages.values().toArray()[0]);
            String creationTimeStamp = page.revisions.get(0).timestamp;
            
            return DatatypeConverter.parseDateTime(creationTimeStamp).getTime();
            
        }
	
	class MyJson { // ensures nice serialization of classes below
		@Override
		public String toString() { return gson.toJson(this); }
	}
	
	class WpQuery extends MyJson {
		Map<String, WpPage> pages;
		JsonObject backlinks; // or use customized class
		// ...
	}
	
	class WpQueryContinue extends MyJson {
		Map<String, String> query, revisions, backlinks; // ...
	}

	class WpPage extends MyJson {
		String pageid;
		int ns;
		String title;
		List<WpRevision> revisions;
		// ...
	}
	
	class WpRevision extends MyJson {
		long revid;
		long parentid;
		String user;
                String contentformat;
                String timestamp;
                @SerializedName("*") String content;
		//...
	}
}
